package com.yidu.ladder.system.controller;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.yidu.ladder.system.domain.Org;
import com.yidu.ladder.system.domain.User;
import com.yidu.ladder.system.domain.UserVo;
import com.yidu.ladder.system.service.UserService;
import com.yidu.ladder.util.IDGenerator;
import com.yidu.ladder.util.MD5Util;


@Controller
@RequestMapping("/system/")
public class UserController {

	@Autowired
	private UserService userService;

	
	
	
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public UserController(UserService userService) {
		super();
		this.userService = userService;
	}
	public UserController() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * 
	 * @Title: queryUser
	 * @Description: 查询所有用户和检索用户信息
	 * @param userVo 用户包装类
	 * @return 返回给前台页面所需的信息
	 * @author ChenLin
	 * @date 2019-12-04 10:12:06
	 */
	@ResponseBody
	@RequestMapping(value = "user",method = RequestMethod.GET)
	public Map<String, Object> queryUser(UserVo userVo) {
		// 执行分页查询用户方法
		Map<String, Object> userMap = userService.pageQueryUser(userVo);
		// 返回查询后的结果
		return userMap;
	}
	
	/**
	 * 
	 * @Title: frozenAndRestoreUser
	 * @Description: 冻结和还原用户
	 * @param userIdstr 用户Id
	 * @param useable 状态
	 * @return 执行后的结果
	 * @author ChenLin
	 * @date 2019-12-04 10:06:56
	 */
	@ResponseBody
	@RequestMapping(value="user/{userId}/{useable}",method=RequestMethod.DELETE)
	public String frozenAndRestoreUser(@PathVariable("userId") String userIdstr, @PathVariable("useable") String useable) {
		// 执行根据ID修改用户状态方法
		boolean result = userService.updateUserUseableById(userIdstr, useable);
		// 判断执行后的结果集是否为false
		if(result==false) {
			// 返回一个字符串fail给页面
			return "fail";
		}
		// 返回一个字符串success给页面
		return "success";
	}
	
	/**
	 * 
	 * @Title: addUser
	 * @Description: 添加用户
	 * @param user 用户实体类
	 * @return 执行后的结果
	 * @author ChenLin
	 * @date 2019-12-04 10:09:51
	 */
	@ResponseBody
	@RequestMapping(value = "user", method = RequestMethod.POST)
	public int addUser(User user) {
		// 将页面输入的密码加密后重新设置password的值
		user.setPassword(MD5Util.MD5Encode(user.getPassword(), "UTF-8"));
		System.err.println(user.getPassword());
		  user.setUserId(IDGenerator.getId());
		  System.out.println(user.getUserId());
		 
			int result = userService.addUser(user);
			return result;
		 } 
	/**
	 * 
	 * @Title: updateUserById
	 * @Description:根据ID修改用户
	 * @param user 用户实体类
	 * @return 1为修改成功，0为失败
	 * @author ChenLin
	 * @date 2019-12-04 10:10:35
	 */
	@RequestMapping(value = "user", method = RequestMethod.PUT)
	@ResponseBody
	public Map<String, Object> updateUserById(User user, HttpServletRequest request) {
		user.setPassword(MD5Util.MD5Encode(user.getPassword(), "UTF-8"));
		 	// 执行根据Id修改用户方法
			int result = userService.updateUserById(user);
			User userObj = null;
			if (result == 1) {
				userObj = userService.findUserById(user.getUserId());
				request.getSession().setAttribute("user", userObj);
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result", result);
			map.put("user", userObj);
			// 返回修改后结果
			return map;
		 } 
	
	
	/**
	 * 
	 * @Title: queryAllOrg
	 * @Description: 查询所有组织
	 * @return 所有组织信息
	 * @author ChenLin
	 * @date 2019-12-04 10:11:20
	 */
	@RequestMapping(value = "org",method = RequestMethod.POST)
	@ResponseBody
	public List<Org> queryAllOrg(){
		List<Org> list = userService.queryAllOrg();
		return list;
	}
	
	

	/**
	 * 图片上传
	 * @param file
	 * @param request
	 * @return
	 */
	 	@ResponseBody
	    @RequestMapping("upload")
	    public Map<String, Object> upload(MultipartFile file){
		 //保存到哪个盘	
		 String panfu = "D:";   
		 	String prefix="";
	        String dateStr="";
	        //保存上传
	        OutputStream out = null;
	        InputStream fileInput=null;
	        try{
	            if(file!=null){
	                String originalName = file.getOriginalFilename();
	                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
	                Date date = new Date();
	                String uuid = UUID.randomUUID().toString();
	                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	                dateStr = simpleDateFormat.format(date);
	                String filepath = "/UserHeadImage" +"/"+ dateStr+"/"+ uuid + "." + prefix;
	                String savePath = panfu + filepath;
	                File files=new File(savePath);
	                if(!files.getParentFile().exists()){
	                	files.getParentFile().mkdirs();
	                }
	                file.transferTo(files);
	                Map<String, Object> map = new HashMap<String, Object>();
	                map.put("src", filepath);
	                return map;
	            }

	        }catch (Exception e){
	        }finally{
	            try {
	                if(out!=null){
	                    out.close();
	                }
	                if(fileInput!=null){
	                    fileInput.close();
	                }
	            } catch (IOException e) {
	            }
	        }
			return null;
	    }
	

	//添加用户时判断手机号是否可用===重名校验

		@RequestMapping(value="/toVerifyUserPhone",method=RequestMethod.POST)
		@ResponseBody
		public Map<String, Object> toVerifyUsername(String userPhone) {
			System.err.println("判断手机号是否存在执行成功~");
			Map<String, Object> map = new HashMap<String, Object>();
			//根据手机号查询用户信息(包括status为0的   以防恢复引起bug)
			User user = userService.toVerifyUserPhone(userPhone);
			map.put("data", user);
			// 判断是否查询到该用户的信息
			if(user==null){
				System.out.println("可用添加");
				map.put("msg", "可用注册");
		   //返回true则为没有该手机号可以被添加
			return map;	
		}else {
			System.out.println("不可添加");
			// 返回false说明数据库用该手机号，不可添加
			map.put("msg", "该手机号已经存在");
			return map;
		}
	  }
		
		
		/**
		 * 
		 * @Title: toVerifyPassword
		 * @Description: 修改密码时判断密码是否存在
		 * @param userId
		 * @param oldPassword
		 * @return
		 * @author ChenLin
		 * @date 2019-12-13 11:12:09
		 */
		@RequestMapping(value="/toVerifyUserPassword",method=RequestMethod.POST)
		@ResponseBody
		public Map<String, Object> toVerifyPassword(String userId,String oldPassword) {
			System.err.println("判断旧密码是否存在执行成功~");
			System.err.println(userId +"---"+oldPassword);
			Map<String, Object> map = new HashMap<String, Object>();
			//根据手机号查询用户信息(包括status为0的   以防恢复引起bug)
			User user = userService.findUserById(userId);
			System.err.println("用户："+user);
			map.put("data", user);
			// 判断输入的密码和查询后的密码是否一致
			if(!user.getPassword().equals(MD5Util.MD5Encode(oldPassword, "UTF-8"))){
				// 不一致为1
				map.put("res", 1);
				map.put("msg", "改尼玛呢！旧密码输入有误");
			return map;	
		}else {
			System.out.println("输入正确");
			// 一致的话为0
			map.put("res", 0);
			map.put("msg", "旧密码输入正确");
			return map;
		}
	  }
		
		
		@RequestMapping(value = "findUserById",method = RequestMethod.GET)
		@ResponseBody
		public Map<String, Object> findUserById(String userId){
			User user = userService.findUserById(userId);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("user", user);
			return map;
		}
		
		@RequestMapping(value = "updatePassword",method = RequestMethod.PUT)
		@ResponseBody
		public Map<String, Object> updatePassword (String userId,String newPassword){
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("res", userService.updatePassword(userId, MD5Util.MD5Encode(newPassword, "UTF-8")));
			
			return map;
		}
}
